package course.controller;

import com.alibaba.excel.EasyExcel;
import course.filter.ExcelListener;
import course.pojo.entity.College;
import course.pojo.excelModel.CollegeModel;
import course.service.*;
import course.service.impl.*;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 导入
 *
 * @author HLF
 * @date 2022/7/6 18:20
 */
@WebServlet("/admin/bathImportController")
@MultipartConfig
public class BathImportController extends BaseController {
    private CollegeService collegeService = new CollegeServiceImpl();

    private StudentService studentService = new StudentServiceImpl();

    private ZhuanyeService zhuanyeService = new ZhuanyeServiceImpl();

    private SubjectService subjectService = new SubjectServiceImpl();

    private TeacherService teacherService = new TeacherServiceImpl();

    protected void college(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part excel = req.getPart("excel");
        String submittedFileName = excel.getSubmittedFileName();
        String fileType = submittedFileName.substring(submittedFileName.lastIndexOf("."));
        if (!(".xls".equalsIgnoreCase(fileType) || ".xlsx".equalsIgnoreCase(fileType))) {
            req.setAttribute("importMsg", "导入文件类型必须为xls或xlsx");
            req.getRequestDispatcher("/admin/collegeController?fun=index").forward(req, resp);
        }

        List<CollegeModel> collegeModels = new ArrayList<>();
        ExcelListener<CollegeModel> excelListener = new ExcelListener<>(collegeModels);
        EasyExcel.read(excel.getInputStream(), CollegeModel.class, excelListener).sheet().doRead();

        if (collegeModels.isEmpty()) {
            req.setAttribute("importMsg", "导入文件内容不能为空");
            req.getRequestDispatcher("/admin/collegeController?fun=index").forward(req, resp);
        }


        List<College> colleges = collegeModels.stream().map(collegeModel -> {
            College college = new College();
            try {
                BeanUtils.copyProperties(college, collegeModel);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return college;
        }).collect(Collectors.toList());

        colleges.forEach(college -> {
            collegeService.addCollege(college);
        });

        req.getRequestDispatcher("/admin/collegeController?fun=index").forward(req, resp);
    }
}












